package com.cynteka.cyfoman.ui;

import com.cynteka.cyfoman.core.Util;
import com.sun.corba.se.impl.orbutil.closure.Constant;
import org.apache.commons.chain.Catalog;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.impl.ContextBase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.List;

/**
 * User: Sergey
 * Date: 02.08.11
 * Time: 17:32
 */
public class TabbedMainForm implements IComponentProvider, BeanFactoryAware {
    private JTabbedPane tabbedPane;
    private JPanel mainPanel;

    private List<Component> components;
    private List<Icon> icons;
    private String name = getClass().getName();
    private BeanFactory beanFactory;
    private ChangeListener changeListener = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            Catalog catalog = Util.getCatalog(beanFactory);
            Command cmd = catalog.getCommand(Constants.TAB_CHANGED_COMMAND);
            if(cmd != null) {
                try {
                    cmd.execute(new ContextBase());
                } catch (Exception e1) {
                    // TODO add logging
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    };

    public List<Component> getComponents() {
        return components;
    }

    public void setComponents(List<Component> components) {
        this.components = components;
        tabbedPane.removeAll();
        int idx = 0;
        for (Component component : components) {
            // TODO redesign titling and ico-ing of tab
            tabbedPane.add(component.getName(), component);
            if (icons != null && icons.size() > idx && icons.get(idx) != null) {
                tabbedPane.setIconAt(idx, icons.get(idx));
            }
            idx++;
        }
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Component getComponent() {
        initListener();
        return mainPanel;
    }

    private void initListener() {
        tabbedPane.removeChangeListener(changeListener);
        tabbedPane.addChangeListener(changeListener);
    }

    public List<Icon> getIcons() {
        return icons;
    }

    public void setIcons(List<Icon> icons) {
        this.icons = icons;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
